package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entities.Utente;

import sessions.AbilitaManagerRemote;
import sessions.RichiestaAiutoManagerRemote;
import staticHtml.PaginaStatica;

public class InviaRispostaAiutoServlet extends HttpServlet {

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		rispondi(request,response);
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		rispondi(request,response);
	}


	private void rispondi(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub

		response.setContentType("text/html");

		PrintWriter out = response.getWriter();
		Utente user= (Utente) request.getSession().getAttribute("utente");

		if(user==null)
		{
			out.println(PaginaStatica.top());
		}
		else
		{
			out.println(PaginaStatica.topUser());
		}

		long richiesta=Long.parseLong(request.getParameter("richiesta"));
		String responso=request.getParameter("responso");
		String risposta=request.getParameter("risposta");
		
		if(risposta.length()<1)
		{
			out.println("Non hai inserito la risposta<br><a href='visualizzaRichiesteAiuto.html'> Torna alla richieste di aiuto </a>");
			out.println(PaginaStatica.bottom());
			return;
		}


		Hashtable<String,String> env = new Hashtable<String,String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		env.put(Context.PROVIDER_URL,"localhost:1099");
		InitialContext jndiContext;
		try {
			jndiContext = new InitialContext(env);

			Object ref = jndiContext.lookup("RichiestaAiutoManager/remote");
			RichiestaAiutoManagerRemote r = (RichiestaAiutoManagerRemote) ref;

			boolean re;
			if(responso.compareTo("yes")==0)
				re=true;
			else
				re=false;

			r.rispondiAiuto(richiesta, re, risposta);
			RequestDispatcher disp = request.getRequestDispatcher("visualizzaRichiesteAiuto.html");
			try {
				disp.forward(request, response);
			} catch (ServletException e) {
				e.printStackTrace();
			}
			out.println(PaginaStatica.bottom());
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
